﻿package com.adsame.utils {
	import flash.events.*;
	import flash.net.*;
	import flash.utils.*;

	import com.adsame.interfaces.*;
	import com.adsame.core.*;
	import com.adsame.exceptions.*;
	import com.adsame.adapters.*;

	/**
	 * AsamXmlLoader 
	 * 
	 * @uses IAsamLoader
	 * @package 
	 * @version $id$
	 * @copyright Powered By Adsame 2008-2009 (c)
	 * @author olga 
	 * @license 
	 */
	public class AsamXmlLoader implements IAsamLoader
	{
		/* ==================== 成员变量定义开始 ==================== */

		protected var __callback : Function = null;

		protected var __scope : Object = null;
		/* ==================== 成员变量定义结束 ==================== */


		/* ==================== 成员方法定义开始 ==================== */

		protected function set callback(callback : Function) : void
		{
			this.__callback = callback;
		}
		protected function set scope(scope : Object) : void
		{
			this.__scope = scope;
		}
		protected function get callback() : Function
		{
			return this.__callback;
		}
		protected function get scope() : Object
		{
			return this.__scope;
		}

		/**
		 * load 
		 *
		 * 载入一个外部的XML文件，
		 * 载入完成调用回调函数loadComplete
		 * 
		 * @param url : String $url : String 
		 * @param callback : Function $callback : Function 
		 * @param scope : String $scope : Object 
		 * @access public
		 * @return void
		 */
		public function load(url : String, callback : Function, scope : Object) : void
		{
			this.callback = callback;
			this.scope = scope;

			// 为每次访问的url地址加上随机数，以防止浏览器cache
			var url: String = url;
			url += (url.indexOf("?") != -1) ? "&" : "?";
			url += "asrand=" + getTimer();

			var url_req : URLRequest = new URLRequest(url);
			var loader : URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, this.loadComplete);
			loader.load(url_req);
		}

		/**
		 * loadComplete 
		 *
		 * 将载入的外部XML文件解析成XML类，再调用用户定义的回调函数
		 * 
		 * @param event : Event $event : Event 
		 * @access protected
		 * @return void
		 */
		protected function loadComplete(event : Event) : void
		{
			var callback : Function = this.callback;

			try {
				XML.ignoreWhitespace = true;
				var xml_data : XML = new XML(event.target.data);
			} catch (e) {
				// 如果xml数据载入或者解析出错，可以在这里报告错误
				throw new AsamSysCodeException("100002");
			}

			var data : Object = AsamXml2ObjectAdapter.parse(xml_data);
			var ad_params : IAsamParams = new AsamParams(data);
			callback.call(this.scope, ad_params);
		}
		/* ==================== 成员方法定义结束 ==================== */
	}
}
